package user

import (
	"common/mildware"
	"common/models"
	"common/validate"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"project/docModel"
	"strconv"
)

func (h UHandler) AddImagToUser(c *gin.Context) {
	resp := new(models.RespData)
	req := new(docModel.AddImagToUserReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("User:AddImagToUser with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("User:AddImagToUser with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//获得ID
	ID, _, _, err := mildware.GetCyrrentUserID(c)
	if err != nil {
		zap.L().Error("User:AddImagToUser mildware.GetCyrrentUserID", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	exist, info, err := h.M.UserCheckId(ID)
	if err != nil {
		zap.L().Error("User:AddImagToUser  h.M.UserCheckId", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	if !exist {
		resp.SendCode(c, models.CodeUserNotExist)
		return
	}
	//获得image的信息
	mExist, imgInfo, err := h.M.ImgInfoCheckByID(req.ImgID)
	if !mExist {
		resp.SendServerBusy(c)
		return
	}
	info.ImgId = strconv.Itoa(int(imgInfo.ID))
	info.ImgHttp = models.GetHttpUrl(imgInfo.ImageId, models.HttpImg)
	info.ImgSrc = imgInfo.Src
	//更新用户
	if err := h.M.UserUpdateById(info); err != nil {
		zap.L().Error("User:AddImagToUser  h.M.UserUpdateById", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	resp.SendSuccess(c)
}
